package us.icitap.cm;

import java.util.logging.Logger;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import us.icitap.cm.business.ActionEnum;
import us.icitap.cm.business.AppUser;
import us.icitap.cm.business.ejb.IAppStatelessBean;
import us.icitap.cm.ui.custom.CustButton;
import us.icitap.cm.ui.policecase.CaseLayout;
import us.icitap.cm.ui.policecase.DisplayCaseLayout;
import us.icitap.cm.ui.policecase.EventReportLayout;
import us.icitap.cm.ui.policecase.PoliceCodeLayout;
import us.icitap.cm.ui.policecase.SupplementReportLayout;
import us.icitap.cm.utils.HandleNotification;
import us.icitap.cm.utils.TPUtil;
import us.icitap.cm.utils.convertes.MyConverterFactory;
import us.icitap.timsportal.business.SimpleUser;
import us.icitap.utils.Result;


import com.vaadin.annotations.PreserveOnRefresh;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.Resource;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.server.VaadinServletRequest;
import com.vaadin.server.ClientConnector.DetachEvent;
import com.vaadin.server.ClientConnector.DetachListener;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Component;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

/**
 * Main UI class
 */
@Theme("cmtheme")
@SuppressWarnings("serial")
@Title("Manaxhimi Policor i Ceshtjes")
@PreserveOnRefresh
public class CaseManagementUI extends UI {

	public static IAppStatelessBean appStatelessBean;
	
	public final static Logger LOG = Logger.getLogger("CommandCenter_LOG");
	final Panel panel = new Panel();
	private String returnURL;
	private CMMenuBar menubar = new CMMenuBar(this);
	private CaseLayout caseLayout;
	private DisplayCaseLayout displayCaseLayout;
	private EventReportLayout erLayout;
	private SupplementReportLayout srLayout;
	private PoliceCodeLayout pcLayout;
	
//	@WebServlet(value = "/*", asyncSupported = true)
//	@VaadinServletConfiguration(productionMode = false, ui = CaseManagementUI.class, widgetset = "us.icitap.cm.widgetset.CasemanagementWidgetset")
//	public static class Servlet extends VaadinServlet {
//	}
	
	
	@Override
	protected void init(VaadinRequest request) {
		_devInit();
	}

	private void _devInit(){
		this.loadResources();
		this.loadDevUser();
		
		this.loadUI();
	}
	
	public void _init(VaadinRequest request){
		this.loadResources();
		
		VaadinServletRequest vaadinRequest = (VaadinServletRequest) request;
		HttpServletRequest httpRequest = vaadinRequest.getHttpServletRequest();
		TPUtil portalUtil = new TPUtil(httpRequest);

		boolean isValid = false;
		if(portalUtil.checkRequestParams() && portalUtil.isValidPortalEntry()){
			isValid = portalUtil.loadUserOnSession();
		}
		System.out.println(isValid);
		if(!isValid){
			getUI().getPage().setLocation(TPUtil.PORTAL_LOCATION);
			getSession().close();
		} else {
			this.returnURL= portalUtil.getReturnURL();
			loadUser((SimpleUser)httpRequest.getSession().getAttribute(TPUtil.USER));		
			loadUI();
		}
		
	}
	
	private void loadDevUser(){
		Result<AppUser> result = appStatelessBean.devLogin();
		System.out.println(result.getObject().getUsername());
		if(result.isSucceeded()){
			
			this.getUI().getSession().setAttribute(AppUser.class, result.getObject());
		}
		else{
			HandleNotification.showErrorOnScreen(result.getMessage());
		}
	}
	
	private void loadUser(SimpleUser portalUser) {
		Result<AppUser> result = appStatelessBean.login(portalUser);
		if(result.isSucceeded()){
			
			this.getUI().getSession().setAttribute(AppUser.class, result.getObject());
		}
		else{
			HandleNotification.showErrorOnScreen(result.getMessage());
		}
				
	}
	
	private void loadUI(){
		this.addStyleName("sfond");
		
		VaadinSession.getCurrent().setConverterFactory(new MyConverterFactory());
		
		final VerticalLayout layout = new VerticalLayout();
		layout.setMargin(false);
		setContent(layout);
		layout.addStyleName("head");
		Resource res = new ThemeResource("img/timsLogo.jpg");
		Image image = new Image(null, res);
		layout.addComponent(image);
		
		layout.setSizeUndefined();
		layout.setWidth("100%");
		
		CustButton closeBtn = new CustButton("TIMS");
		closeBtn.addClickListener(new Button.ClickListener() {			
			

			@Override
			public void buttonClick(ClickEvent event) {
				getUI().getPage().setLocation(returnURL);
				getSession().getSession().setMaxInactiveInterval(0);
			}
		});
		
		HorizontalLayout hl = new HorizontalLayout();
		hl.setStyleName("menuBackground");
		hl.setSizeFull();
		
		//closeBtn.setStyleName(Runo.BUTTON_LINK);
		hl.addComponent(closeBtn);
		hl.addComponent(menubar );
		hl.setExpandRatio(menubar, 1);
	
		layout.addComponent(hl);
		
		
		layout.addComponent(panel);
		
		panel.addStyleName("panelCaption");
		panel.addStyleName("cust-margin-4");
		
		
		panel.setWidth("99%");
		
		VerticalLayout vl = new VerticalLayout();
		vl.setSizeFull();
		vl.setHeight("600px");
		
		panel.setContent(vl);
		
		panel.getContent().addStyleName("logo");
		
		
		GridLayout footerVl = new GridLayout(2,1);
		
		footerVl.addStyleName("footer");
		footerVl.setWidth("99%");
		footerVl.setHeight("50px");
		footerVl.setMargin(true);
		
		
		
		Label l = new Label(this.getUser().getUsername());
		l.addStyleName("userLabel");
		footerVl.addComponent(l, 0, 0);
		footerVl.setComponentAlignment(l, Alignment.MIDDLE_LEFT);
		
//		if(getUser().getCommandCenter() != null){
//			Label ccName = new Label(getUser().getCommandCenter().getName());
//			ccName.addStyleName("ccLabel");
//			ccName.setSizeUndefined();
//			footerVl.addComponent(ccName);
//			footerVl.setComponentAlignment(ccName, Alignment.MIDDLE_RIGHT);
//			
//		}
		
		layout.addComponent(footerVl);

	}
	
	
	private void loadResources() {
		InitialContext init;
		try {
			init = new InitialContext();
			appStatelessBean = (IAppStatelessBean) init.lookup("java:global/CaseManagement/AppStatelessBean");

		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public void loadCaseLayout(ActionEnum actionEnum){
		
		this.resetLayout();
		this.getUI().getSession().setAttribute(ActionEnum.class, actionEnum);
		this.caseLayout = new CaseLayout();
//		this.panel.setContent(caseLayout);
		
		
	}
	public void loadEventReportLayout(){
		this.resetLayout();
		this.erLayout = new EventReportLayout();
		this.panel.setContent(erLayout);
		
	}
	
	public void loadSupplementReportLayout(){
		this.resetLayout();
		this.srLayout = new SupplementReportLayout();
		this.panel.setContent(srLayout);
	}
	
	public void loadDisplayCaseLayout(){
		this.resetLayout();
		this.displayCaseLayout = new DisplayCaseLayout();
		this.panel.setContent(displayCaseLayout);
	}
	

	private void resetLayout() {
		this.panel.setContent(null);
		
		this.caseLayout = null;
		this.erLayout = null;
		this.srLayout = null;
		this.displayCaseLayout = null;
		this.getUI().getSession().setAttribute(ActionEnum.class, null);
	}
	
	public static ActionEnum getActualAction(){
		return (ActionEnum) CaseManagementUI.getCurrent().getSession().getAttribute(ActionEnum.class.getName());
	}
	
	public static AppUser getUser(){
		return (AppUser)CaseManagementUI.getCurrent().getSession().getAttribute(AppUser.class.getName());
	}

	public void loadPoliceCodeLayout() {
		// TODO Auto-generated method stub
		this.resetLayout();
		this.pcLayout = new PoliceCodeLayout();
		this.panel.setContent(pcLayout);
	}
}